import { PlanDictBean } from "./../plan-dict.bean";
import { Component, OnInit } from "@angular/core";
import { NzNotificationService, UploadFile } from "ng-zorro-antd";
import { Router } from "@angular/router";
import { HttpServcie } from "../../../../service/http.service";
import { Config } from "../../../../service/config";
import { NzModalService, NzModalSubject } from "ng-zorro-antd";
import * as moment from 'moment';

@Component({
  selector: "plan-dict",
  templateUrl: "plan-dict.html",
  styleUrls: ["plan-dict.scss"]
})
export class PlanDict implements OnInit {
  modelTitle: string;
  modal: number;
  updateData: any;
  planDict: PlanDictBean = new PlanDictBean();
  list: any = [];
  allChecked = false;
  indeterminate = false;
  currentModal: any;
  isConfirmLoading = false;
  isAddVisible = false;
  planTypeList = Config.planTypeList;
  config = Config;
  total = 0;
  inDictData: any;
  constructor(
    private httpServcie: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) {
    this.planDict.currentPage = 1;
    this.planDict.pageSize = 10;
    this.planDict.pPartyId = JSON.parse(
      window.localStorage.getItem("user")
    ).partyId;
    // this.query();
  }

  ngOnInit() {
    //do
  }

  query() {

    if (this.planDict.pStartDtShow) {
      this.planDict.pStartDt = moment(this.planDict.pStartDtShow).format(
        "YYYYMMDD"
      );
    } else {
      this.planDict.pStartDt = null;
    }
    if (this.planDict.pEndDtShow) {
      this.planDict.pEndDt = moment(this.planDict.pEndDtShow).format(
        "YYYYMMDD"
      );
    } else {
      this.planDict.pEndDt = null;
    }
    this.httpServcie.queryPlanDict(this.planDict).subscribe(data => {
      if (data.status == 200) {
        this.list = data.data.list;
        this.total = data.data.total;
      } else if (data.status == 401) {
        this._notification.create("error", "失败", "请重新登录");
        this.router.navigateByUrl("/login");
      } else {
        this._notification.create("error", "失败", "查询出错！请重试");
      }
    });
  }

  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.list.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event) {
    this.planDict.pageSize = event;
    this.planDict.currentPage = 1;
    this.query();
  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.planDict.currentPage = event;
    this.query();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.planDict.currentPage = event;
    this.query();
  }

  //添加
  //this.isAddVisible = true;
  add(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "添加";
    this.modal = 0;

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 600,
      style: {
        top: "40px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  delete() {
    const updateList: any = [];
    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = Object.assign({}, element);
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    let thiss = this;
    this.modalService.confirm({
      title: "您是否确认要删除这项内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let ob = thiss.httpServcie.deletePlanDict({
          id: thiss.updateData.id
        });
        ob.subscribe(
          data => {
            if (data.status == 200) {
              thiss._notification.create("success", "成功", "删除成功");
              thiss.planDict.currentPage = 1;
              thiss.query();
            } else if (data.status == 401) {
              thiss._notification.create("error", "失败", "请重新登录");
              thiss.router.navigateByUrl("/login");
            } else {
              thiss._notification.create("error", "失败", "查询出错！请重试");
            }
          },
          error => {
            this._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() { }
    });
  }
  //修改
  update(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "修改";
    this.modal = 1;
    const updateList: any = [];

    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = Object.assign({}, element);
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 600,
      style: {
        top: "40px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  //添加添加页面的数据
  handleOk(e) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 1000);
    // this.isAddConfirmLoading = true;
    // this.inValue = "aaaaa";
  }

  //关闭model框
  handleCancel = e => {
    console.log(e);
    this.isAddVisible = false;
  };

  //添加后返回的结果
  addOutPut(event) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 500);
    //this.planDict.currentPage = 1;
    this.query();
  }

  //导入计划明细
  importPlanD(title, content, footer, data) {
    this.inDictData = Object.assign({}, data);
    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 500,
      style: {
        top: "40px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  showPD(data) {
    this.router.navigate(["/home/plan-detail", data]);
  }

  importCheckItem(title, content, footer, data) {
    this.modelTitle = "检查项目";
    this.modal = 2;
    this.updateData = Object.assign({}, data);
    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 800,
      style: {
        top: "40px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  //上传回调
  uploadChage(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      if (info.file.response.status != "200") {
        this._notification.create(
          "error",
          "错误提示",
          info.file.response.message
        );
      } else {
        this._notification.create("success", "提示", "导入成功");
        this.currentModal.destroy();
      }
    }
  }

  download(url, name) {
    let link = document.createElement("a");
    let body = document.querySelector("body");

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(
      blob => {
        link.href = window.URL.createObjectURL(blob);
        link.download = name;
        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    );
  }
  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }
}
